<template>
  <div
    class="toolbar-button-wrapper"
    :class="{ 'is-button-type': type === 'button' }"
  >
    <!-- Button 类型 -->
    <ToolbarButton
      v-if="type === 'button'"
      v-bind="buttonAttrs"
      @click="handleClick"
      @dblclick="handleDoubleClick"
    >
      <template v-if="$slots.icon" #icon>
        <slot name="icon"></slot>
      </template>
      <template v-if="!$slots.icon">
        <slot></slot>
      </template>
    </ToolbarButton>

    <!-- Select 类型 -->
    <ToolbarSelect
      v-else-if="type === 'select'"
      v-bind="selectAttrs"
      @update:model-value="handleSelectChange"
      @change="handleSelectChange"
    >
      <template v-if="$slots.option" #option="{ option }">
        <slot name="option" :option="option"></slot>
      </template>
    </ToolbarSelect>

    <!-- Popover 类型 -->
    <ToolbarPopover
      v-else-if="type === 'popover'"
      v-bind="popoverAttrs"
      @show="handlePopoverShow"
      @before-enter="handlePopoverBeforeEnter"
      @after-enter="handlePopoverAfterEnter"
      @hide="handlePopoverHide"
      @before-leave="handlePopoverBeforeLeave"
      @after-leave="handlePopoverAfterLeave"
    >
      <div v-if="iconValue" :class="iconClass"></div>
      <slot v-else-if="$slots.icon" name="icon"></slot>
      <slot v-else></slot>

      <template #popover>
        <slot name="popover"></slot>
      </template>
    </ToolbarPopover>

    <!-- Dropdown 类型 - 使用 ToolbarDropdown 组件 -->
    <ToolbarDropdown
      v-else-if="type === 'dropdown'"
      v-bind="dropdownAttrs"
      @main-click="handleMainClick"
    >
      <template v-if="$slots.icon" #icon>
        <slot name="icon"></slot>
      </template>
      <template v-if="$slots.default" #default>
        <slot></slot>
      </template>
      <template #dropdown>
        <slot name="dropdown"></slot>
      </template>
    </ToolbarDropdown>
  </div>
</template>

<script setup lang="ts">
import { computed, useAttrs, inject } from "vue";
import { ToolbarButton, ToolbarSelect, ToolbarPopover, ToolbarDropdown } from "./src";
import type { ToolbarButtonProps } from "../../types";
import type { StyleValue } from "vue";
import type { PopoverPlacement, PopoverTrigger } from "./src/button.types";

defineOptions({
  inheritAttrs: false,
  name: "ToolbarButtonContainer",
});

const props = withDefaults(defineProps<ToolbarButtonProps>(), {
  type: "button",
  options: () => [],
});

const emit = defineEmits([
  "click",
  "dblclick",
  "update:modelValue",
  "change",
  "popover-show",
  "popover-before-enter",
  "popover-after-enter",
  "popover-hide",
  "popover-before-leave",
  "popover-after-leave",
  "main-click",
  "dropdown-click",
]);

const attrs = useAttrs();

// 驼峰转短横线
const camelToKebab = (str: string): string => {
  return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
};

// 从 attrs 或 props 中获取属性值（支持驼峰和短横线格式）
const getAttrValue = <T>(key: string, defaultValue?: T): T | undefined => {
  // 先尝试直接获取（驼峰格式）
  if (attrs[key as keyof typeof attrs] !== undefined) {
    return attrs[key as keyof typeof attrs] as T;
  }
  // 再尝试从 props 获取（驼峰格式）
  if ((props as any)[key] !== undefined) {
    return (props as any)[key] as T;
  }
  // 尝试短横线格式
  const kebabKey = camelToKebab(key);
  if (attrs[kebabKey as keyof typeof attrs] !== undefined) {
    return attrs[kebabKey as keyof typeof attrs] as T;
  }
  // 尝试从 props 获取（短横线格式）
  if ((props as any)[kebabKey] !== undefined) {
    return (props as any)[kebabKey] as T;
  }
  return defaultValue;
};

// 模板中使用的计算属性
const iconValue = computed(() => getAttrValue<string>("icon"));

const iconClass = computed(() => iconValue.value || "");

// 合并 props 和 attrs，用于透传所有属性
const buttonAttrs = computed(() => {
  // 先获取所有属性，确保 hideText 有正确的默认值
  const hideTextValue = getAttrValue<boolean>("hideText", true);
  
  // 从 attrs 中排除 hideText，避免 undefined 覆盖我们的默认值
  const { hideText: _, ...restAttrs } = attrs;
  
  return {
    ...restAttrs,
    icon: getAttrValue<string>("icon"),
    title: getAttrValue<string>("title"),
    hideText: hideTextValue, // 确保 hideText 有正确的默认值 true，不会被 undefined 覆盖
    shortcut: getAttrValue<string>("shortcut"),
    tooltip: getAttrValue<string>("tooltip"),
    largeIcon: getAttrValue<boolean>("largeIcon", false),
    active: getAttrValue<boolean>("active", false),
    disabled: getAttrValue<boolean>("disabled", false),
    round: getAttrValue<boolean>("round", false),
    circle: getAttrValue<boolean>("circle", false),
  };
});

const selectAttrs = computed(() => {
  // 优先使用 props 中的值，然后使用 attrs，最后使用默认值
  return {
    "model-value":
      props.modelValue ?? attrs["model-value"] ?? attrs["modelValue"],
    placeholder:
      ((props.placeholder ?? attrs.placeholder) as string) ?? "请选择",
    options: ((props.options ?? attrs.options) as any[]) ?? [],
    clearable: ((props.clearable ?? attrs.clearable) as boolean) ?? false,
    filterable: ((props.filterable ?? attrs.filterable) as boolean) ?? false,
    multiple: ((props.multiple ?? attrs.multiple) as boolean) ?? false,
    "select-width":
      ((props.selectWidth ??
        attrs["select-width"] ??
        attrs["selectWidth"]) as string) ?? "120px",
    disabled: ((props.disabled ?? attrs.disabled) as boolean) ?? false,
  };
});

const popoverAttrs = computed(() => {
  // 先获取关键属性值
  const hideTextValue = getAttrValue<boolean>("hideText", true);
  const titleValue = getAttrValue<string>("title");
  const iconValue = getAttrValue<string>("icon");
  const activeValue = getAttrValue<boolean>("active", false);
  const largeIconValue = getAttrValue<boolean>("largeIcon", false);
  
  // 从 attrs 中排除已显式处理的属性（包括驼峰和短横线格式），避免覆盖
  const {
    hideText: _1,
    "hide-text": _2,
    title: _3,
    icon: _4,
    active: _5,
    largeIcon: _6,
    "large-icon": _7,
    ...restAttrs
  } = attrs;
  return {
    placement: getAttrValue<PopoverPlacement>("popoverPlacement", "bottom"),
    width: getAttrValue<string | number>("popoverWidth", 200),
    trigger: getAttrValue<PopoverTrigger>("popoverTrigger", "click"),
    disabled: getAttrValue<boolean>("disabled", false),
    "popper-class": getAttrValue<string>("popperClass", ""),
    "popper-style": getAttrValue<StyleValue>("popperStyle", {}),
    // 显式传递按钮相关属性，确保这些值优先于 attrs 中的值
    title: titleValue,
    icon: iconValue,
    active: activeValue,
    largeIcon: largeIconValue,
    hideText: hideTextValue,
    // 其他未处理的 attrs 放在最后
    ...restAttrs,
  };
});

// Dropdown 属性
const dropdownAttrs = computed(() => {
  const hideTextValue = getAttrValue<boolean>("hideText", true);
  const titleValue = getAttrValue<string>("title");
  const iconValue = getAttrValue<string>("icon");
  const activeValue = getAttrValue<boolean>("active", false);
  const largeIconValue = getAttrValue<boolean>("largeIcon", false);
  
  // 从 attrs 中排除已显式处理的属性
  const {
    hideText: _1,
    "hide-text": _2,
    title: _3,
    icon: _4,
    active: _5,
    largeIcon: _6,
    "large-icon": _7,
    ...restAttrs
  } = attrs;
  
  return {
    placement: getAttrValue<PopoverPlacement>("popoverPlacement", "bottom"),
    trigger: getAttrValue<"click" | "hover">("popoverTrigger", "click"),
    disabled: getAttrValue<boolean>("disabled", false),
    hideText: hideTextValue,
    dropdownIcon: getAttrValue<string>("dropdownIcon", "i-ri-arrow-down-s-fill"),
    customClass: getAttrValue<string>("popperClass", ""),
    customStyle: getAttrValue<StyleValue>("popperStyle", {}),
    // 显式传递按钮相关属性
    title: titleValue,
    icon: iconValue,
    active: activeValue,
    largeIcon: largeIconValue,
    // 其他未处理的 attrs 放在最后
    ...restAttrs,
  };
});

// 事件处理函数
const handleClick = (event: MouseEvent) => {
  emit("click", event);
};

const handleDoubleClick = (event: MouseEvent) => {
  emit("dblclick", event);
};

const handleSelectChange = (value: any) => {
  emit("update:modelValue", value);
  emit("change", value);
};

const handleMainClick = (event: MouseEvent) => {
  emit("main-click", event);
};

// Popover 事件处理
const handlePopoverShow = () => {
  emit("popover-show");
};

const handlePopoverBeforeEnter = () => {
  emit("popover-before-enter");
};

const handlePopoverAfterEnter = () => {
  emit("popover-after-enter");
};

const handlePopoverHide = () => {
  emit("popover-hide");
};

const handlePopoverBeforeLeave = () => {
  emit("popover-before-leave");
};

const handlePopoverAfterLeave = () => {
  emit("popover-after-leave");
};
</script>

<style scoped>
/* 最外层容器 */
.toolbar-button-wrapper {
  display: inline-block;
  margin: 0 2px;
}

/* Button 类型添加圆角 */
.toolbar-button-wrapper.is-button-type {
  border-radius: var(--editor-radius-medium);
  overflow: hidden;
}
</style>
